package test.administrator.example.com.mvptest1.framework.support.viewstate.lce.fragment;

import test.administrator.example.com.mvptest1.framework.MvpPresenter;
import test.administrator.example.com.mvptest1.framework.lce.MvpLceView;
import test.administrator.example.com.mvptest1.framework.lce.impl.fragment.MvpLceFragment;
import test.administrator.example.com.mvptest1.framework.support.fragment.FragmentMvpDelegate;
import test.administrator.example.com.mvptest1.framework.support.viewstate.MvpViewStateDelegateCallback;
import test.administrator.example.com.mvptest1.framework.support.viewstate.ViewState;
import test.administrator.example.com.mvptest1.framework.support.viewstate.fragment.FragmentMvpViewStateDelegateImpl;
import test.administrator.example.com.mvptest1.framework.support.viewstate.lce.LceViewState;

/**
 * 代理对象特点
 * 特点一：实现目标接口
 * 特点二：持有目标对象引用
 * Created by thinkpad on 2018/8/13.
 */
public abstract class MvpLceViewStateFragment<M, V extends MvpLceView<M>, P extends MvpPresenter<V>, VS extends LceViewState<M, V>> extends MvpLceFragment<M, V, P> implements MvpLceView<M>, MvpViewStateDelegateCallback<V, P, VS> {

	/**
	 * 持有目标对象引用
	 *
	 * @return
	 */
	@Override
	protected FragmentMvpDelegate<V, P> getMvpDelegate() {
		if (mvpDelegate == null) {
			mvpDelegate = new FragmentMvpViewStateDelegateImpl<>(this, this, true, true);
		}
		return mvpDelegate;
	}

	/******************集成ViewState功能********************/
	protected VS viewState;
	//是否正在恢复
	private boolean restoringViewState = false;

	@Override
	public VS getViewState() {
		return viewState;
	}

	@Override
	public void setViewState(VS viewState) {
		this.viewState = viewState;
	}

	@Override
	public void setRestoringViewState(boolean restoringViewState) {
		this.restoringViewState = restoringViewState;
	}

	@Override
	public boolean isRestoringViewState() {
		return restoringViewState;
	}
	/******************集成ViewState功能********************/

	/******************集成LCE实现********************/
	@Override
	public void showContent() {
		super.showContent();
		viewState.setStateShowContent(getData());
	}

	@Override
	public void showError(Throwable e, boolean isPullToRefresh) {
		super.showError(e, isPullToRefresh);
		viewState.setStateShowError(e, isPullToRefresh);
	}

	@Override
	public void showLoading(boolean pullToRefresh) {
		super.showLoading(pullToRefresh);
		viewState.setStateShowLoading(pullToRefresh);
	}

	@Override
	public void onNewViewStateInstance() {
		loadData(false);
	}

	@Override
	public void onViewStateInstanceRestored(boolean instanceStateRetained) {
		//不是恢复状态，并且是需要加载状态
		if (!instanceStateRetained && viewState.isLoadingState()) {
			loadData(viewState.isPullToRefreshLoadingState());
		}
	}

	public abstract M getData();

	/******************集成LCE实现********************/

}
